
using System;
using System.Linq;
using Microsoft.Xna.Framework;
using Tama_Chan.GameEngine_ns;
using Tama_Chan.Utils;


namespace Tama_Chan.Entities_ns
{
   public class Mystery : GameEntity
   {
      public Mystery(GameEngine gameEngine)
      {
         GameEngine =  gameEngine;
         Texture = gameEngine.MysteryTexture;
         IsDead = true;
         SoundOne = GameEngine.MysterySoundEffect.CreateInstance();
         ColorArray = new []{Color.LawnGreen, Color.Tomato, Color.Yellow};
         Reset();
      }


      public override void Update(GameTime gameTime)
      {
         // If player is attacking, do nothing.
         if(GameEngine.PowerPellet.State == PowerPelletState.Attacking)
         {
            return;
         }

         AccumulatedTicksOne += gameTime.ElapsedGameTime.Ticks;
         if(IsDead && AccumulatedTicksOne > IntervalOne)
         {
            IsDead = false;
         }

         if(!IsDead)
         {
            AccumulatedTicksTwo += gameTime.ElapsedGameTime.Ticks;
            if(AccumulatedTicksTwo > IntervalTwo)
            {
               Color = GetColor();
               AccumulatedTicksTwo -= IntervalTwo;
            }

            AccumulatedTicksThree += gameTime.ElapsedGameTime.Ticks;
            if(AccumulatedTicksThree > LifeTime)
            {
               Reset();
            }
         }

         base.Update(gameTime);
      }


      public override void Draw()
      {
         if(!IsDead)
         {
            GameEngine.Game1.SpriteBatch.Draw(Texture, Position, Color);
         }

         base.Draw();
      }


      public void Reset()
      {
         IsDead = true;
         Color = GetColor();
         ScoreValue = Random.Next(100, 5000);
         ColorArrayCurrentIndex = 0;

         int right = GameEngine.Game1.GameBounds.Right - 80 - Bounds.Width;
         int left = GameEngine.Game1.GameBounds.Left + 80;
         int top = GameEngine.Game1.GameBounds.Top + 80;
         int bottom = GameEngine.Game1.GameBounds.Bottom - 80 - Bounds.Height;
         Position = new Vector2(Random.Next(left, right), Random.Next(top, bottom));

         // Delay before appearing
         IntervalOne = Random.Next((int)GeneralUtils.GetSecondsAsTicks(2f), (int)GeneralUtils.GetSecondsAsTicks(60f));
         AccumulatedTicksOne = 0;

         // How often it changes color
         IntervalTwo = GeneralUtils.GetSecondsAsTicks(.15f);
         AccumulatedTicksTwo = 0;

         // Lifetime
         LifeTime = TimeSpan.TicksPerSecond * 3;
         AccumulatedTicksThree = 0;
      }


      private Color GetColor()
      {
         Color color = ColorArray[ColorArrayCurrentIndex];
         ColorArrayCurrentIndex++;
         if(ColorArrayCurrentIndex > ColorArray.Count() - 1)
         {
            ColorArrayCurrentIndex = 0;
         }
         return color;
      }

   }
}
